const request = require('co-request');
const fs = require('fs');
const cfs = require('co-fs');
const Joi = require('joi');
const HttpStatus = require('http-status-codes');

const API = require('../../config/API');
const UploadValidation = require('./upload.validation');
const CheckValidation = require('./check.validation');


function *uploadFile() {
  const credentials = {
    id: this.req.body.id,
    path: this.req.file.path,
  };

  const validateResult = Joi.validate(credentials, UploadValidation.uploadSchema);
  if (validateResult.error) {
    this.throw(HttpStatus.BAD_REQUEST, validateResult.error.details[0].message);
  }

  const formData = yield {
    file: fs.createReadStream(credentials.path),
  };

  try {
    const result = yield request.post({
      uri: `${API.uploadServer}uuid=${credentials.id}`,
      formData: formData,
    });
    yield cfs.unlink(credentials.path);
    this.body = result.body;
  } catch (error) {
    this.throw(HttpStatus.BAD_REQUEST, error.message);
  }
}

function *checkStatus() {
  const credentials = {
    ticket: this.request.body.ticket
  };
  const validateResult = Joi.validate(credentials, CheckValidation.checkSchema);

  if (validateResult.error) {
    this.throw(HttpStatus.BAD_REQUEST, validateResult.error.details[0].message);
  }

  try {
    const result = yield request.get({
      uri: `${API.checkServer}${credentials.ticket}`,
    });
    this.body = result.body;
  } catch (error) {
    this.throw(HttpStatus.BAD_REQUEST, error.message);
  }
}

const uploadController = {
  uploadFile,
  checkStatus,
};

module.exports = uploadController;
